/**
 * 优化功能状态管理
 */

import { create } from 'zustand';
import { devtools, persist } from 'zustand/middleware';

interface OptimizationAnalysis {
  task_id: string;
  status: string;
  overall_score: number;
  content_length: number;
  created_at: string;
  scores: Record<string, number | null>;
  suggestions_count: number;
  high_priority_count: number;
}

interface OptimizationState {
  // 当前分析结果
  currentAnalysis: OptimizationAnalysis | null;
  
  // 分析状态
  isAnalyzing: boolean;
  analysisError: string | null;
  
  // 建议选择
  selectedSuggestions: string[];
  appliedSuggestions: string[];
  
  // 优化历史
  optimizationHistory: Array<{
    taskId: string;
    timestamp: string;
    articleId?: string;
    score: number;
  }>;
  
  // 配置
  config: {
    autoApplyBasicRules: boolean;
    priorityFilter: string[];
    enabledTypes: string[];
  };
  
  // Actions
  setCurrentAnalysis: (analysis: OptimizationAnalysis | null) => void;
  setAnalyzing: (isAnalyzing: boolean) => void;
  setAnalysisError: (error: string | null) => void;
  
  toggleSuggestion: (suggestionId: string) => void;
  selectAllSuggestions: (suggestionIds: string[]) => void;
  clearSelection: () => void;
  
  addAppliedSuggestion: (suggestionId: string) => void;
  clearAppliedSuggestions: () => void;
  
  addToHistory: (entry: any) => void;
  clearHistory: () => void;
  
  updateConfig: (config: Partial<OptimizationState['config']>) => void;
  resetStore: () => void;
}

const initialState = {
  currentAnalysis: null,
  isAnalyzing: false,
  analysisError: null,
  selectedSuggestions: [],
  appliedSuggestions: [],
  optimizationHistory: [],
  config: {
    autoApplyBasicRules: true,
    priorityFilter: ['high', 'medium'],
    enabledTypes: ['structure', 'coherence', 'fluency', 'keyword', 'title']
  }
};

export const useOptimizationStore = create<OptimizationState>()(
  devtools(
    persist(
      (set, get) => ({
        ...initialState,
        
        setCurrentAnalysis: (analysis) => set({ 
          currentAnalysis: analysis,
          analysisError: null 
        }),
        
        setAnalyzing: (isAnalyzing) => set({ isAnalyzing }),
        
        setAnalysisError: (error) => set({ 
          analysisError: error,
          isAnalyzing: false 
        }),
        
        toggleSuggestion: (suggestionId) => set((state) => {
          const isSelected = state.selectedSuggestions.includes(suggestionId);
          const isApplied = state.appliedSuggestions.includes(suggestionId);
          
          // 不能选择已应用的建议
          if (isApplied) {
            return state;
          }
          
          if (isSelected) {
            return {
              selectedSuggestions: state.selectedSuggestions.filter(
                (id) => id !== suggestionId
              )
            };
          } else {
            return {
              selectedSuggestions: [...state.selectedSuggestions, suggestionId]
            };
          }
        }),
        
        selectAllSuggestions: (suggestionIds) => set((state) => {
          // 过滤掉已应用的建议
          const validIds = suggestionIds.filter(
            (id) => !state.appliedSuggestions.includes(id)
          );
          return { selectedSuggestions: validIds };
        }),
        
        clearSelection: () => set({ selectedSuggestions: [] }),
        
        addAppliedSuggestion: (suggestionId) => set((state) => ({
          appliedSuggestions: [...state.appliedSuggestions, suggestionId],
          selectedSuggestions: state.selectedSuggestions.filter(
            (id) => id !== suggestionId
          )
        })),
        
        clearAppliedSuggestions: () => set({ appliedSuggestions: [] }),
        
        addToHistory: (entry) => set((state) => {
          const newHistory = [entry, ...state.optimizationHistory];
          // 保留最近20条记录
          if (newHistory.length > 20) {
            newHistory.pop();
          }
          return { optimizationHistory: newHistory };
        }),
        
        clearHistory: () => set({ optimizationHistory: [] }),
        
        updateConfig: (config) => set((state) => ({
          config: { ...state.config, ...config }
        })),
        
        resetStore: () => set(initialState)
      }),
      {
        name: 'optimization-storage',
        partialize: (state) => ({
          optimizationHistory: state.optimizationHistory,
          config: state.config
        })
      }
    )
  )
);